//
//  SearchViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-12.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "SearchViewController.h"

#import "UserInfoViewController.h"
#import "ViewControllerChooser.h"

#import "TwitterClient.h"
#import "User1.h"
#import "Entry.h"
#import "SearchResultViewController.h"
#import "DataManager.h"


@implementation SearchViewController

//@synthesize tweetSearchCell;
//@synthesize userSearchCell;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];
	top10 = [[NSMutableArray alloc] init];
	id obj = [DataManager loadObjectFromFile:@"top10.dat"];
	if(obj){
		if([obj isKindOfClass:[NSArray class]]){
			NSArray *arr = (NSArray *)obj;
			[top10 setArray:arr];
		}
	}
	[NSThread detachNewThreadSelector:@selector(loadTop10) toTarget:self withObject:nil];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	self.tabBarController.navigationItem.title = NSLocalizedString(@"SEARCH",@"");
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/


/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	[top10 removeAllObjects];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger ret = 0;
	switch (section) {
		case 0:
			ret = 2;
			break;
		case 1:
			ret = [top10 count];
			if(ret == 0){
				ret = 1;
			}
			break;

		default:
			break;
	}
	return ret;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSString *ret = @"";
	switch (section) {
		case 0:
			ret =  NSLocalizedString(@"SEARCH",@"");
			break;
		case 1:
			ret = NSLocalizedString(@"TOPTEN",@"");
			break;

		default:
			break;
	}
	return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
    
    // Set up the cell...
	/*
     If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list.
     */
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	NSString *tt = @"";
	if(section == 0){
		switch (row) {
			case 0:
				tt = @"Tweet";
				break;
			case 1:
				tt = @"Users";
				break;
			default:
				break;
		}
	}else if(section == 1){
		NSInteger cn = [top10 count];
		if(cn > 0){
			NSDictionary *dict = (NSDictionary *)[top10 objectAtIndex:row];
			tt = (NSString *)[dict objectForKey:@"name"];
		}else{
			tt = @"Loading...";
		}
	}
	cell.textLabel.text = tt;
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
    
    // TODO 注意 Top10 采用 数组内部含有 NSDictionary 方式进行操作
    NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	SearchResultViewController *vc;
	if(section == 0){
		// TODO 0, 1 搜索
		// SearchResultViewController *vc = [[SearchResultViewController alloc] initWithNibName:@"SearchResultViewController" bundle:nil];
		ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
		vc = (SearchResultViewController *)[chooser choose:VC_SEARCH_RESULT];
		switch (row) {
			case 0:
				vc.searchType = ST_TWEET;
				break;
			case 1:
				vc.searchType = ST_USER;
				break;
			default:
				break;
		}
		vc.renew = YES;
		[self.navigationController pushViewController:vc animated:YES];
	}else if(section == 1){
		NSInteger cn = [top10 count];
		if(cn == 0){
			if(row == 0){
				if(!loading){
					[NSThread detachNewThreadSelector:@selector(loadTop10) toTarget:self withObject:nil];
				}
			}
		}else{
			// TODO top10响应
			NSDictionary *dict = (NSDictionary *)[top10 objectAtIndex:row];
			NSString *name = (NSString *)[dict objectForKey:@"name"];
			NSString *url = (NSString *)[dict objectForKey:@"url"];
#ifdef DEBUG
			NSLog(@"Trend %@ url is %@",name,url);
#endif
			if(url){
				// TODO 获取参数
				NSRange rang = [url rangeOfString:@"=" options:NSBackwardsSearch];
				if(rang.location != NSNotFound){
					NSString *q = [url substringFromIndex:(rang.location + rang.length)];
#ifdef DEBUG
					NSLog(@"Trends q %@",q);
#endif
					// SearchResultViewController *vc = [[SearchResultViewController alloc] initWithNibName:@"SearchResultViewController" bundle:nil];
					ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
					vc = (SearchResultViewController *)[chooser choose:VC_SEARCH_RESULT];
					vc.searchType = ST_TRENDS;
					vc.searchKeyword = name;
					vc.renew = YES;
					[self.navigationController pushViewController:vc animated:YES];
				}
			}
		}
	}
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -

#pragma mark LoadData methods

- (void)loadTop10{
	loading = YES;
	TwitterClient *client = [TwitterClient getInstance];
	[client doTrends:top10];
	[self.tableView reloadData];
	loading = NO;
	[DataManager saveObjectToFile:top10 withName:@"top10.dat"];
}

#pragma mark -

- (void)dealloc{
//	[userSearchCell release];
//	[tweetSerachCell release];
	[top10 release];
    [super dealloc];
}


@end

